<template>
  <div style="padding-bottom: 10px">
    <a-space>
      <a-button
        type="primary"
        status="danger"
        :disabled="selectedKeys.length === 0"
        @click="handleBatchDelete"
      >
        批量删除
      </a-button>
      <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
    </a-space>
  </div>
  <a-table
    row-key="_id"
    :data="datalist"
    :columns="columns"
    :loading="loading"
    :pagination="{
      total: count,
      current: current,
      pageSize: pageSize,
      showTotal: true,
      showPageSize: true,
    }"
    :row-selection="{
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    }"
    v-model:selectedKeys="selectedKeys"
    @page-change="handlePageChange"
    @page-size-change="handlePageSizeChange"
  >
    <template #index="{ rowIndex }">
      {{ rowIndex + 1 + (current - 1) * pageSize }}
    </template>
    <template #nick="{ record }">
      {{ record.nick }}
    </template>
    <template #content="{ record }">
      <a-typography-paragraph
        editable
        v-model:editText="record.content"
        @edit-end="handleEditContent(record)"
      >
        {{ record.content }}
      </a-typography-paragraph>
    </template>
    <template #logs="{ record }">
      {{ record.logs }}
    </template>
    <template #istask="{ record }">
      <div v-if="!record.istask">未分配</div>
      <div v-else>
        <a-button-group>
          <a-button>{{ record.triggerTime }}</a-button>
          <a-tooltip content="重置">
            <a-button @click="handleResetTask(record)">
              <template #icon>
                <icon-sync />
              </template>
            </a-button>
          </a-tooltip>
        </a-button-group>
      </div>
    </template>
    <template #isok="{ record }">
      <div>{{ record.submitnum }}次</div>
      <div v-if="record.isfriend">成功</div>
    </template>
  </a-table>
</template>

<script lang="ts" setup>
  import { ref, watch, reactive } from 'vue';
  import { Message, Modal, TableColumnData } from '@arco-design/web-vue';
  import {
    saveGroupFriendTask,
    delGroupFriendTask,
    getGroupFriendTask,
    editGroupFriendTask,
    resetGroupFriendTask,
  } from '@/api/task';
  //   import Task from './friend-task.vue';
  const props = defineProps<{
    selectedWxid: string;
  }>();
  interface FormValues {
    typename: string;
    wxid: string;
    content: string;
  }
  const form1 = reactive({
    typename: '',
    wxid: '',
    content: '',
  });
  // 搜索表单数据
  const searchForm = ref({
    isok: undefined,
    istask: undefined,
  });
  const datalist = ref([]);
  const current = ref(1);
  const pageSize = ref(10);
  const count = ref(0);
  const loading = ref(false);
  const selectedKeys = ref<string[]>([]);
  const resData = reactive({
    ownerWxid:  '',
    groupwxid:  ''
  });
  const columns: TableColumnData[] = [
    {
      title: '#',
      dataIndex: 'index',
      slotName: 'index',
      width: 70,
    },
    {
      title: '类别',
      dataIndex: 'typename',
      width: 70,
    },
    {
      title: 'wxid',
      dataIndex: 'friendwxid',
      width: 150,
    },
    {
      title: '昵称',
      slotName: 'nick',
      width: 150,
    },
    {
      title: '招呼',
      slotName: 'content',
      width: 150,
    },
    {
      title: '计划分配',
      slotName: 'istask',
      width: 150,
    },
    {
      title: '执行',
      slotName: 'isok',
    },
  ];

  // 获取好友列表数据
  const fetchFriendList = async () => {
    loading.value = true;
    try {
      const res: any = await getGroupFriendTask({
        ownerWxid:props.selectedWxid,
        field: {
        //   isok: searchForm.isok,
        //   istask: searchForm.istask,
        },
        page: current.value,
        pageSize: pageSize.value,
      });
      if (res.code === 20000) {
        count.value = res.data.count;
        datalist.value = res.data.list;
      } else {
        Message.error(res.msg || '获取任务列表失败');
      }
    } catch (error) {
      console.error('获取任务列表失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 处理页码变化
  const handlePageChange = async (page: number) => {
    current.value = page;
    await fetchFriendList();
  };
  // 处理每页条数变化
  const handlePageSizeChange = async (size: number) => {
    pageSize.value = size;
    current.value = 1; // 切换页面大小时重置为第一页
    await fetchFriendList();
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedKeys.value.length === 0) {
      Message.warning('请选择要删除的好友');
      return;
    }

    const handleConfirm = async () => {
      try {
        const res: any = await delGroupFriendTask({
          ids: selectedKeys.value,
        });

        if (res.code === 20000) {
          Message.success('批量删除成功');
          selectedKeys.value = []; // 清空选中项
          await fetchFriendList();
        } else {
          Message.error(res.msg || '批量删除失败');
        }
      } catch (error) {
        Message.error('批量删除失败');
      }
    };

    Modal.warning({
      title: '删除确认',
      content: `确定要删除选中的 ${selectedKeys.value.length} 个手机号吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: handleConfirm,
    });
  };

  const handleForm1Submit = async (data: any) => {
    // 调用 savetask 接口保存数据
    loading.value = true;
    try {
      const res: any = await saveGroupFriendTask({
        ownerWxid: data.selectedWxid,
        groupwxid: data.groupwxid,
        friendlist: data.friendlist,
        content: data.content,
      });
      if (res.code === 20000) {
        Message.success('保存成功');
        resData.ownerWxid = data.selectedWxid;
        resData.groupwxid = data.groupwxid;
        await fetchFriendList();
        loading.value = false;
      } else {
        Message.error(res.msg || '保存失败');
      }
    } catch (error) {
      Message.error('保存失败');
    }
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.value = {
      isok: undefined,
      istask: undefined,
    };
    current.value = 1;
    fetchFriendList();
  };

  const handleEditContent = async (record: any) => {
    try {
      const res: any = await editGroupFriendTask({
        record,
      });

      if (res.code === 20000) {
        Message.success('修改成功');
        await fetchFriendList();
      } else {
        Message.error(res.msg || '修改失败');
      }
    } catch (error) {
      Message.error('修改失败');
    }
  };

  const handleResetTask = async (record: any) => {
    try {
      const res: any = await resetGroupFriendTask({
        record,
      });

      if (res.code === 20000) {
        Message.success('重置成功');
        await fetchFriendList();
      } else {
        Message.error(res.msg || '重置失败');
      }
    } catch (error) {
      Message.error('重置失败');
    }
  };

  watch(
    () => props.selectedWxid,
    async (newWxid) => {
      if (newWxid) {
        await fetchFriendList();
      }
    },
    { immediate: true }
  );

  // 暴露方法给父组件
  defineExpose({
    handleForm1Submit
  });
</script>
